package com.song.controller;


import com.song.config.CustomUserDetails;
import com.song.dao.IUser;
import com.song.pojo.Result;
import com.song.pojo.ResultMsg;
import com.song.pojo.UserModel;
import com.song.util.JwtUtils;
import com.song.util.UserLoginInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLIntegrityConstraintViolationException;

@RestController
@RequestMapping("user")
//用户 登录系统
public class UserController {


    @Autowired
    private IUser iUser;
    @Autowired
    private JwtUtils jwtUtils;

    //    注册
    @PostMapping("/register")
    @Transactional
    public ResultMsg register(@RequestBody UserModel user, HttpSession session) throws SQLIntegrityConstraintViolationException {
        if (user == null) {
            return Result.error(1, "数据不能为空");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (null == user.getPwd()) {
            return Result.error(1, "无效密码");
        }
        user.setType(1);
        user.setPwd(encoder.encode(user.getPwd()));
        Integer result = iUser.saveOneUser(user);
//			插入用户角色关联表
        if (0 < result) {
            return Result.success();
        }
        return Result.error();
    }

    //查询是否是qq登录
    @RequestMapping("qqlogin")
    public ResultMsg getQQMessage(UserModel userModel) {
//qq 授权登录，绑定网站账号

        iUser.saveOneUser(userModel);

        return Result.success();

    }

    // 获取用户是否登录
    @RequestMapping("getlogininfo")
    public ResultMsg getUserLoginInfo(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        final String auth_token_start = "Bearer ";
        if (!StringUtils.isEmpty(authorization)) {

            String substring = authorization.substring(auth_token_start.length());

            CustomUserDetails userFromToken = jwtUtils.getUserFromToken(substring);
            String name = userFromToken.getUsername();

            if (!StringUtils.isEmpty(name))
                return Result.success("用户已登录");

        }
        return Result.error(1, "用户未登录！");
    }



}

